<?php
namespace App\Http\Controllers;
use App\Form;
use App\Formitem;
use App\Comment;
use App\FY\FeiyuApi;
use App\Message;
use App\Post;
use App\Postmeta;
use App\Tag;
use App\TagGroup;
use App\Usermeta;
use App\User;
use Validator;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends Controller
{
    private function CurrentUser(){
        $currentUser = Auth::user();
        $meta = Usermeta::where("user_id",$currentUser->id)->get();
        foreach ($meta as $m){
            $currentUser["$m->key"] = $m->value;
        }
        return $currentUser;
    }
    private function getQR($id){
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxfca50078ea0ff5c1&secret=845bd4e72e18887e19170550c49af3ed';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $json = curl_exec($ch);
        curl_close($ch);
        $json = json_decode($json);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$json->access_token;
        $post_data = array ("path" => "pages/view/view?id=".$id."&&type=active","width" => 430);
        $post_data = json_encode($post_data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            file_put_contents("upload/view/$id.jpg", $tmpInfo);
            return asset("upload/view/$id.jpg");
        }
    }
    public function admin()
    {
        return view('admin.admin',[
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    private function metaSave($postId,$key,$value,$id,$del=null){
        if($id){
            $Postmeta = Postmeta::find($id);
            if($del){
                $Postmeta->delete();
            }else{
                $Postmeta->value = $value;
                $Postmeta->save();
            }
        }else{
            $Postmeta = new Postmeta();
            $Postmeta->post_id = $postId;
            $Postmeta->key = $key;
            $Postmeta->value = $value;
            $Postmeta->save();
        }
    }
    public function FormItem(){
        $FormItems = Formitem::orderBy('id', 'desc')->paginate(10);
        return view('admin.formitem',[
            'formItems' => $FormItems,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function FormItemSave(Request $request){
        $data = $request->input('FormItem');
//        var_dump($data);
        $value = Array();
        $i = 0;
        while (isset($data['item_'.$i])){
//            array_push($arr,$data['item_'.$i]);
            $arr = Array();
            $arr["type"] = $data['item_'.$i.'_t'];
            $arr["name"] = $data['item_'.$i];
            $arr["placeholder"] = $data['item_'.$i.'_p'];
            array_push($value,$arr);
            $i++;
        }

        if(isset($data['id'])){
            $FormItem = Formitem::find($data['id']);

            $FormItem->name = $data["name"];
            $FormItem->value = json_encode($value, JSON_UNESCAPED_UNICODE);
            if($FormItem->save()){
                return redirect('admin/formitem/edit/'.$data['id'])->with('success','更新成功');
            }else{
                return redirect('admin/formitem/edit/'.$data['id'])->with('fail','更新失败');
            }
        }else{
        $FormItem = new Formitem();

        $FormItem->name = $data["name"];
        $FormItem->value = json_encode($value, JSON_UNESCAPED_UNICODE);
        if($FormItem->save()){
            return redirect('admin/formitem')->with('success','新增成功');
        }else{
            return redirect('admin/formitem')->with('fail','新增失败');
        }
        }
    }
    public function FormItemDel($id){
        $FormItem = Formitem::find($id);
        if($FormItem->delete()){
            return redirect('admin/formitem')->with('success','删除成功');
        }else{
            return redirect('admin/formitem')->with('fail','删除失败');
        }
    }
    public function FormItemEdit($id){
        $FormItem = Formitem::find($id);
        $FormItem->value = json_decode($FormItem->value);
        $typeName = Array("text"=>"文本","textarea"=>"文本框","time"=>"时间","picker"=>"选项","phone"=>"手机验证",);
        foreach ($FormItem->value as $f){
            $f->typeName = $typeName[$f->type];
        }
        return view('admin.formedit',[
            'FormItem' => $FormItem,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Form(Request $request){
        $Input = $request->input();
        $Form = Form::orderBy('id', 'desc');
        $name = null;
        if($request->has('id')){
            $name = Formitem::find($Input["item"]);
            $name = json_decode($name->value);
            $Form = $Form->where('parent',$Input["id"])->where('item',$Input["item"])->get();
        }elseif($request->has('type')){
            $Form = $Form->where('type',$Input["type"])->paginate(20);
        }else{
            $Form = $Form->paginate(20);
        }
        $TypeName = Array("service"=>"服务预约","active"=>"活动申请","join"=>"活动预约","user"=>"入驻申请");
        foreach ($Form as $f){
            $Post = null;
            if($f->parent!=0){
                $Post = Post::find($f->parent);
            }
            $f->form = json_decode($f->form);
            $f->title = $f->parent!=0&&$Post?$Post->title:0;
            $f->typeName = $TypeName["$f->type"];
        }
//        dd($Form,$name);
        return view('admin.form',[
            "CurrentUser"=>$this->CurrentUser(),
            "Forms"=>$Form,
            "Name"=>$name
        ]);
    }
    public function FormDel($id){
        $Form = Form::find($id);
        if($Form->delete()){
            return redirect('admin/form')->with('success','删除成功');
        }else{
            return redirect('admin/form')->with('fail','删除失败');
        }
    }
    public function FormEdit($id){
        $Form = Form::find($id);
        $value = json_decode($Form->form);
        $name = Array();
        if($Form->item){
            $items = Formitem::find($Form->item);
            $item = json_decode($items->value);
            for ($i=0;$i<count($item);$i++){
                array_push($name,$item[$i]->name);
            }
        }
        return view('admin.formview',[
            "CurrentUser"=>$this->CurrentUser(),
            "Form"=>$Form,
            "Value"=>$value,
            "Name"=>$name
        ]);
    }

    //评论功能
    public function Comment(){
        $Comments = Comment::orderBy('id', 'desc')->paginate(20);
        foreach ($Comments as $Comment){
            $Post = Post::find($Comment->post_id);
            $Comment->title = $Post?$Post->title:"已删除";
        }
        return view('admin.comment',[
            'Comments' => $Comments,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function CommentDel($id){
        $Comment = Comment::find($id);
        if($Comment->delete()){
            return redirect('admin/comment')->with('success','删除成功');
        }else{
            return redirect('admin/comment')->with('fail','删除失败');
        }
    }

    //展示功能
    public function Tag($type){
        $tags = Tag::where('type',$type)->paginate(20);
        return view('admin.tag',[
            'Tags' => $tags,
            'type' => $type,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function TagSave(Request $request){
        $data = $request->input('Tag');

        if(isset($data['id'])){
            $Tag = Tag::find($data['id']);

            $Tag->name = $data["name"];
            if(isset($data["more"])){
                $Tag->more = $data["more"];
            }
            if($Tag->save()){
                return redirect('admin/tag/edit/'.$data['id'])->with('success','更新成功');
            }else{
                return redirect('admin/tag/edit/'.$data['id'])->with('fail','更新失败');
            }
        }else{
            $Tag = new Tag();

            $Tag->name = $data["name"];
            $Tag->type = $data["type"];
            if(isset($data["more"])){
                $Tag->more = $data["more"];
            }

            if($Tag->save()){
                return redirect('admin/tag/'.$data['type'])->with('success','新增成功');
            }else{
                return redirect('admin/tag/'.$data['type'])->with('fail','新增失败');
            }
        }

    }
    public function TagEdit($id){
        $Tag = Tag::find($id);
        return view('admin.tagedit',[
            'Tag' => $Tag,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function TagDel($id){
        $Tag = Tag::find($id);
        if($Tag->type!='xcx'&&$Tag->delete()){
            return redirect('admin/tag/'.$Tag->type)->with('success','删除成功');
        }else{
            return redirect('admin/tag/'.$Tag->type)->with('fail','删除失败');
        }
    }

    //私信功能
    public function Message(){
        $Messages = Message::orderBy('id', 'desc')->paginate(20);
        foreach ($Messages as $item){
            if($item->get_user==0){
                $item->getName = '全部用户';
                $item->postName = '系统公告';
            }else{
                $user = User::find($item->get_user);
                $item->getName = $user?$user->name:"0";
                $user = User::find($item->post_user);
                $item->postName = $user?$user->name:"0";
            }
        }
        return view('admin.message',[
            'Messages' => $Messages,
            'type'=>'all',
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function MessageView($id){
        $Msg = Message::find($id);
        if($Msg->parent != 0){
            $parent = $Msg->parent;
        }else{
            $parent = $id;
        }
        $Messages = Message::whereRaw('parent = ? OR id = ?',[$parent,$parent])->orderBy('id', 'desc')->paginate(20);
        foreach ($Messages as $item){
            if($item->get_user==0){
                $item->getName = '全部用户';
                $item->postName = '系统公告';
            }else{
                $user = User::find($item->get_user);
                $item->getName = $user?$user->name:"0";
                $user = User::find($item->post_user);
                $item->postName = $user?$user->name:"0";
            }
        }
        return view('admin.message',[
            'Messages' => $Messages,
            'type'=>'view',
            'view'=>$id,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function MessageDel($id){
        $Msg= Message::find($id);
        if($Msg->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function MessageDelView($id,$view){
        $Msg= Message::find($id);
        if($view&&$view==$id){
            if($Msg->parent != 0){
                $parent = $Msg->parent;
            }else{
                $parent = $id;
            }
            $Message = Message::whereRaw('(parent = ? OR id = ?) AND id != ?',[$parent,$parent,$id])->first();
            if($Msg->delete()){
                if($Message){
                    return redirect('admin/message/view/'.$Message->id)->with('success','删除成功');
                }else{
                    return redirect('admin/message')->with('success','删除成功');
                }
            }else{
                return redirect()->back()->with('fail','删除失败');
            }
        }
        if($Msg->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }
    public function MessageAdd(Request $request){
        if($request->has("id")){
            $Message = Message::find($request->input('id'));
            $User = User::find($Message->post_user);
            $Message->name = $User->name;
        }else{
            $Message = null;
        }
        return view('admin.messageadd',[
            "CurrentUser"=>$this->CurrentUser(),
            "Message"=>$Message
        ]);
    }
    public function MessageSave(Request $request){
        $data = $request->input('Message');
        $type = isset($data['more'])?1:0;

        $Message = new Message();
        $Message -> content = $data['content'];
        $User = $this->CurrentUser();
        $Message -> post_user = $User["id"];

        if(!$type){
            if(isset($data['id'])){
                $Message->get_user = $data['get_user'];
                $Message->parent = $data['parent']?$data['parent']:$data['id'];
            }else{
                $get_user = Uesr::where('name',$data['name'])->first();
                if($get_user){
                    $Message->get_user = $get_user->id;
                }else{
                    return redirect()->back()->with('fail','找不到对应用户');
                }
            }
        }
        if($Message->save()){
            return redirect()->back()->with('success','发布成功');
        }else{
            return redirect()->back()->with('fail','发布失败');
        }
    }

    //展示功能
    public function Post(){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        return view('admin.post',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "forms"=>$forms,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function PostSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }

            if(isset($meta)&&isset($meta['active'])&&$data["active"]!='no'){
                $key = [];
                $value = [];
                $arr = (object)[];
                $i = 0;
                while (isset($data['activeKey_'.$i])){
                    array_push($key,$data['activeKey_'.$i]);
                    array_push($value,$data['activeValue_'.$i]);
                    $i++;
                }
                $arr->key = $key;
                $arr->value = $value;
                $this->metaSave($Post->id,'active',json_encode($arr, JSON_UNESCAPED_UNICODE),isset($meta)&&isset($meta['active'])?$meta['active']:null);
            }else if(isset($meta)&&isset($meta['active'])){
                $this->metaSave($Post->id,'active','',$meta['active'],true);
            }

            if(isset($meta)&&isset($meta['form'])&&$data["form"]!='no'){
                if($data["form"]=='0'){
                    $value = [];
                    $arr = (object)[];
                    $i = 0;
                    while (isset($data['form_'.$i])){
                        array_push($value,$data['form_'.$i]);
                        $i++;
                    }
                    $arr->item = $value;
                    $arr->more = 0;

                    $FormItem = new Formitem();
                    $FormItem->name = '自定义';
                    $FormItem->value = json_encode($arr, JSON_UNESCAPED_UNICODE);
                    $FormItem->parent = $Post->id;
                    $FormItem->save();

                    $this->metaSave($Post->id,'form',$FormItem->id,isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }else{
                    $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            if(isset($data["timeStatus"])){
                $this->metaSave($Post->id,'activeTime',$data["time"],isset($meta)&&isset($meta['activeTime'])?$meta['activeTime']:null);
            }else if(isset($meta)&&isset($meta['activeTime'])){
                $this->metaSave($Post->id,'activeTime','',$meta['activeTime'],true);
            }

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }
            return redirect('admin/post/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function PostEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.post',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Posts(Request $request){
        $input = $request->input();
        $TagNum = Tag::where("type","xcx")->where("name","主页")->first();
        $Posts = Post::where("xcx",$TagNum->id);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->tag);
            $Post->tagName = $tag?$tag->name:"已删除";
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","page")->get();
        return view('admin.posts',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function PostDel($id){
        $Post = Post::find($id);
        if($Post->delete()){
            return redirect()->back()->with('success','删除成功');
        }else{
            return redirect()->back()->with('fail','删除失败');
        }
    }

    //用户功能
    public function UserAdd(){
        return view('admin.user',[
            "User"=>null,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserSave(Request $request){
        $data = $request->input('User');
        if(isset($data["id"])){
            $User = User::find($data["id"]);
            if($User->email != $data["email"]){
                $validator = Validator::make($data,[
                    'name' => 'required|max:255',
                    'email' => 'required|email|max:255|unique:users',
                ]);
            }else{
                $validator = Validator::make($data,[
                    'name' => 'required|max:255',
                ]);
            }
        }else{
            $validator = Validator::make($data,[
                'name' => 'required|max:255',
                'email' => 'required|email|max:255|unique:users',
                'password' => 'required|min:6',
            ]);
        }

        if($validator->fails()){
            return redirect()->back()->withErrors($validator)->withInput();
        }

        if(isset($data["id"])){
            $User->name = $data["name"];
            if($User->email != $data["email"])$User->email = $data["email"];
            $User->phone = $data["phone"];
            if($data["password"])$User->password = bcrypt($data['password']);
            if($data["level"])$User->level = $data['level'];

            if($User->save()){
                return redirect()->back()->with('success','修改用户成功');
            }else{
                return redirect()->back()->with('fail','修改用户失败')->withInput();
            }
        }else{
            $User = new User();
            $User->name = $data["name"];
            $User->email = $data["email"];
            $User->phone = $data["phone"];
            $User->password = bcrypt($data['password']);
            $User->level = $data['level'];

            if($User->save()){
                $UserMeta =  new Usermeta();
                $UserMeta->user_id = $User->id;
                $UserMeta->key = 'avatar';
                $UserMeta->value = 'https://sichuangyi.demopp.in/upload/avatar/avatar.png';
                $UserMeta->save();
                return redirect("/admin/users")->with('success','添加用户成功');
            }else{
                return redirect()->back()->with('fail','添加用户失败')->withInput();
            }
        }
    }
    public function Users(){
        $Users = User::orderBy('id', 'desc')->paginate(20);
        foreach ($Users as $user){
            $user->num = Post::where("user_id",$user->id)->count();
        }
        return view("admin.users",[
            "Users"=>$Users,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserEdit($id){
        $User = User::find($id);
        return view("admin.user",[
            "User"=>$User,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserProfile(){
        $User = User::find(Auth::user()->id);
        return view("admin.user",[
            "User"=>$User,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function UserDel($id){
        $User = User::find($id);
        if($User->delete()){
            return redirect('admin/users')->with('success','删除成功');
        }else{
            return redirect('admin/users')->with('fail','删除失败');
        }
    }
    public function wx(){
        return view("auth.wx");
    }

    //服务大厅
    public function Services(Request $request){
        $input = $request->input();
        $TagNum = Tag::where('type','xcx')->where('name','服务')->first();
        $Posts = Post::where('xcx',$TagNum->id);
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->tag);
            $Post->tagName = $tag?$tag->name:"已删除";
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","service")->get();
        return view('admin.services',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Service(){
        $xcxs = Tag::where('type','xcx')->get();
        $services = Tag::where('type','service')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        return view('admin.service',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "tags"=>$tags,
            "forms"=>$forms,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ServiceSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }
            if(isset($data["activeKey_0"])){
                $key = [];
                $value = [];
                $arr = (object)[];
                $i = 0;
                while (isset($data['activeKey_'.$i])){
                    array_push($key,$data['activeKey_'.$i]);
                    array_push($value,$data['activeValue_'.$i]);
                    $i++;
                }
                $arr->key = $key;
                $arr->value = $value;
                $this->metaSave($Post->id,'service',json_encode($arr, JSON_UNESCAPED_UNICODE),isset($meta)&&isset($meta['service'])?$meta['service']:null);
            }else if(isset($meta)&&isset($meta['service'])){
                $this->metaSave($Post->id,'service','',$meta['service'],true);
            }

            if($data["form"]!='no'){
                if($data["form"]=='0'){
                    $value = [];
                    $arr = (object)[];
                    $i = 0;
                    while (isset($data['form_'.$i])){
                        array_push($value,$data['form_'.$i]);
                        $i++;
                    }
                    $arr->item = $value;
                    $arr->more = 0;

                    $FormItem = new Formitem();
                    $FormItem->name = '自定义';
                    $FormItem->value = json_encode($arr, JSON_UNESCAPED_UNICODE);
                    $FormItem->parent = $Post->id;
                    $FormItem->save();

                    $this->metaSave($Post->id,'form',$FormItem->id,isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }else{
                    $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
                }
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            if(isset($data["subtitle"])){
                $this->metaSave($Post->id,'subtitle',$data["subtitle"],isset($meta)&&isset($meta['subtitle'])?$meta['subtitle']:null);
            }else if(isset($meta)&&isset($meta['subtitle'])){
                $this->metaSave($Post->id,'subtitle','',$meta['subtitle'],true);
            }

            if(isset($data["summary"])){
                $this->metaSave($Post->id,'summary',$data["summary"],isset($meta)&&isset($meta['summary'])?$meta['summary']:null);
            }else if(isset($meta)&&isset($meta['summary'])){
                $this->metaSave($Post->id,'summary','',$meta['summary'],true);
            }

            if(isset($data["price"])){
                $this->metaSave($Post->id,'price',$data["price"],isset($meta)&&isset($meta['price'])?$meta['price']:null);
            }else if(isset($meta)&&isset($meta['price'])){
                $this->metaSave($Post->id,'price',0,$meta['price']);
            }


            if(isset($data["phone"])){
                $p = Postmeta::where("post_id",$Post->id)->where("key","phone")->first();
                $f = Postmeta::where("post_id", $Post->id)->where("key", "fy")->first();
                $feiyuApi = new FeiyuApi();
                if($f){
                   if(!$p||$p->value!=$data["phone"]) {
                       $ret = $feiyuApi->modifyAccountDisplayNumberAction($f->value,'86'.$data["phone"]);
                       if($ret["resultCode"]==0){
                           $this->metaSave($Post->id,'phone',$data["phone"],isset($meta)&&isset($meta['phone'])?$meta['phone']:null);
                       };
                   }
                }else{
                    $ret = $feiyuApi->addAccountUrlAction('12332112','86'.$data["phone"]);
                    if($ret["resultCode"]==0){
                        $this->metaSave($Post->id,'fy',$ret["result"]["fyAccountId"],isset($meta)&&isset($meta['fy'])?$meta['fy']:null);
                        if(!$p||$p->value!=$data["phone"]) {
                            $this->metaSave($Post->id,'phone',$data["phone"],isset($meta)&&isset($meta['phone'])?$meta['phone']:null);
                        }
                    }
                }
            }else if(isset($meta)&&isset($meta['phone'])){
                $this->metaSave($Post->id,'phone','',$meta['phone'],true);
            }

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }
            return redirect('admin/service/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ServiceEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $services= Tag::where('type','service')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.service',[
            "xcxs"=>$xcxs,
            "services"=>$services,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }

    //活动路演
    public function Actives(Request $request){
        $input = $request->input();
        $ActiveOne = Tag::where('type','xcx')->where('name','路演')->first();
        $ActiveTwo = Tag::where('type','xcx')->where('name','活动')->first();
        $ActiveThree = Tag::where('type','xcx')->where('name','回顾')->first();
//        $Posts = Post::where('xcx',$ActiveOne->id)->orWhere('xcx',$ActiveTwo->id)->orWhere('xcx',$ActiveThree->id);
        $Posts = Post::where(function($query) use ($ActiveOne,$ActiveTwo,$ActiveThree) {
            $query->where('xcx', $ActiveOne->id)
                ->orWhere(function ($query) use ($ActiveTwo, $ActiveThree) {
                    $query->where('xcx', $ActiveTwo->id)
                        ->orWhere(function ($query) use ($ActiveThree) {
                            $query->where('xcx', $ActiveThree->id);
                        });
                });
            });
        if($request->has("s")){
            $Posts = $Posts->where("title","like","%".$input["s"]."%");
        }
        if($request->has("cat")){
            $Posts = $Posts->where("tag",$input["cat"]);
        }
        if($request->has("tag")){
            $Posts = $Posts->whereHas('TagGroup', function ($query) use ($input) {
                $query->where('tag', $input["tag"]);
            });
        }
        $Posts = $Posts->orderBy('id', 'desc')->paginate(20);
        $status = Array("待审","通过","拒绝");
        foreach ($Posts as $Post) {
            $user = User::find($Post->user_id);
            $Post->user = $user?$user->name:"0";
            $tag = Tag::find($Post->xcx);
            $Post->tagName = $tag?$tag->name:"已删除";
            $Post->statusName = $status[$Post->status];
        }
        $Tags = Tag::where("type","tag")->get();
        $Cats = Tag::where("type","page")->get();
        return view('admin.actives',[
            "Posts"=>$Posts,
            "Tags"=>$Tags,
            "Cats"=>$Cats,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function Active(){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $forms = Formitem::where('parent',0)->get();
        return view('admin.active',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "forms"=>$forms,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }
    public function ActiveSave(Request $request){
        $data = $request->input('Post');
        if($data["id"]){
            $Post = Post::find($data["id"]);
            $Postmeta = Postmeta::where('post_id',$data["id"])->get();
            $meta = [];
            foreach ($Postmeta as $m){
                $meta["$m->key"]= $m->id;
            }
        }else{
            $Post = new Post();
        }

        $Post->title = $data["title"];
        $Post->content = $data["content"];
        $Post->cover = $data["cover"];
        $Post->tag = $data["tag"];
        $Post->xcx = $data["xcx"];
        $Post->level = $data["level"];
        $Post->author = $data["author"];
        $Post->status = $data["status"];

        if($Post->save()){
            if($data["video"]){
                $this->metaSave($Post->id,'video',$data["video"],isset($meta)&&isset($meta['video'])?$meta['video']:null);
            }else if(isset($meta)&&isset($meta['video'])){
                $this->metaSave($Post->id,'video','',$meta['video'],true);
            }
            if($data["mapImage"]){
                $this->metaSave($Post->id,'map',$data["mapImage"],isset($meta)&&isset($meta['mapImage'])?$meta['mapImage']:null);
            }else if(isset($meta)&&isset($meta['mapImage'])){
                $this->metaSave($Post->id,'mapImage','',$meta['mapImage'],true);
            }
            if($data["viewQR"]){
                $this->metaSave($Post->id,'viewQR',$data["viewQR"],isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
            }else{
                $QR = $this->getQR($Post->id);
                if($QR){
                    $this->metaSave($Post->id,'viewQR',$QR,isset($meta)&&isset($meta['viewQR'])?$meta['viewQR']:null);
                }else if(isset($meta)&&isset($meta['viewQR'])){
                    $this->metaSave($Post->id,'viewQR','',$meta['viewQR'],true);
                }
            }

            if($data["form"]!='no'){
                $this->metaSave($Post->id,'form',$data["form"],isset($meta)&&isset($meta['form'])?$meta['form']:null);
            }else if(isset($meta)&&isset($meta['form'])){
                $this->metaSave($Post->id,'form','',$meta['form'],true);
            }

            $this->metaSave($Post->id,'activeTime',$data["time"],isset($meta)&&isset($meta['activeTime'])?$meta['activeTime']:null);
            $this->metaSave($Post->id,'endTime',$data["endTime"],isset($meta)&&isset($meta['endTime'])?$meta['endTime']:null);
            $this->metaSave($Post->id,'city',$data["city"],isset($meta)&&isset($meta['city'])?$meta['city']:null);
            $this->metaSave($Post->id,'area',$data["area"],isset($meta)&&isset($meta['area'])?$meta['area']:null);
            $this->metaSave($Post->id,'address',$data["address"],isset($meta)&&isset($meta['address'])?$meta['address']:null);
            $this->metaSave($Post->id,'latitude',$data["latitude"],isset($meta)&&isset($meta['latitude'])?$meta['latitude']:null);
            $this->metaSave($Post->id,'longitude',$data["longitude"],isset($meta)&&isset($meta['longitude'])?$meta['longitude']:null);
            $this->metaSave($Post->id,'peoples',$data["peoples"],isset($meta)&&isset($meta['peoples'])?$meta['peoples']:null);
            $this->metaSave($Post->id,'price',$data["price"],isset($meta)&&isset($meta['price'])?$meta['price']:null);
            $this->metaSave($Post->id,'organizers',$data["organizers"],isset($meta)&&isset($meta['organizers'])?$meta['organizers']:null);

            $tagGroup = TagGroup::where("post_id",$Post->id)->get();
            $tagOld = ["tag"=>[],"id"=>[]];
            foreach ($tagGroup as $tag){
                array_push($tagOld["tag"],$tag->tag);
                array_push($tagOld["id"],$tag->id);
            }
            if($data["arr"]){
                $tagNew = json_decode($data["arr"]);
                $tagAdd = [];
                $arrLength = count($tagNew);
                for ($i=0;$i<$arrLength;$i++){
                    $n = array_search($tagNew[$i],$tagOld["tag"]);
                    if($n===false){
                        array_push($tagAdd,$tagNew[$i]);
                    }else{
                        array_splice($tagOld["tag"],$n,1);
                        array_splice($tagOld["id"],$n,1);
                    };
                }

                $arrLength = count($tagAdd);
                for ($i=0;$i<$arrLength;$i++){
                    $newTag = new TagGroup();
                    $newTag->post_id = $Post->id;
                    $newTag->tag = $tagAdd[$i];
                    $newTag->save();
                }

                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }else{
                $arrLength = count($tagOld["tag"]);
                for ($i=0;$i<$arrLength;$i++){
                    $dalTag = TagGroup::find($tagOld["id"][$i]);
                    $dalTag->delete();
                }
            }
            return redirect('admin/active/edit/'.$Post->id)->with('success',isset($meta)?'修改成功':'新增成功');
        }else{
            return redirect()->back()->with('fail',isset($meta)?'修改失败':'新增失败');
        }
    }
    public function ActiveEdit($id){
        $xcxs = Tag::where('type','xcx')->get();
        $pages = Tag::where('type','page')->get();
        $tags = Tag::where('type','tag')->get();
        $tagGroup = TagGroup::where('post_id',$id)->get();
        $forms = Formitem::whereRaw('parent = ? OR parent = ?',[0,$id])->get();
        $Post = Post::find($id);
        $Postmeta = Postmeta::where('post_id',$id)->get();
        $meta = [];
        foreach ($Postmeta as $m){
            $meta["$m->key"]= $m->value;
        }
        $group = [];
        foreach ($tagGroup as $t){
            array_push($group,$t->tag);
        }
        return view('admin.active',[
            "xcxs"=>$xcxs,
            "pages"=>$pages,
            "tags"=>$tags,
            "tagGroup"=>json_encode($group),
            "forms"=>$forms,
            "Post"=>$Post,
            "meta"=>$meta,
            "CurrentUser"=>$this->CurrentUser()
        ]);
    }

}